<template>
  <div class="mod-demo-echarts">
    <el-form :inline="true">
      <el-form-item prop="cid">
        <!-- <el-select v-model="dataForm.cid" filterable placeholder="请选择省市区">
          <el-option
            v-for="city in cityList"
            :key="city.id"
            :label="city.cityName"
            :value="city.id"
          >
          </el-option>
        </el-select> -->
        <el-cascader
          :options="cityList"
          :props="{
            checkStrictly: true,
            value: 'id',
            label: 'name',
            children: 'children',
          }"
          v-model="dataForm"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item prop="qjdate">
        <el-date-picker
          v-model="qjdate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getHome()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      stripe
      v-loading="dataListLoading"
      style="width: 100%"
    >
      <el-table-column prop="mobile" label="手机号/账号" width="180">
      </el-table-column>
      <el-table-column prop="province" label="省"> </el-table-column>
      <el-table-column prop="city" label="市"> </el-table-column>
      <el-table-column prop="region" label="区/县"> </el-table-column>
      <el-table-column prop="campusName" label="所属校区名称">
      </el-table-column>
      <el-table-column prop="loginNum" label="登录次数"> </el-table-column>
      <el-table-column prop="loginTime" label="使用时长(小时)">
      </el-table-column>
      <el-table-column prop="userType" label="用户类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.userType == 0">体验账号</el-tag>
          <el-tag v-else-if="scope.row.userType == 1">激活账号</el-tag>
          <el-tag v-else>生成账号</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0" type="danger">禁用</el-tag>
          <el-tag v-else>启用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间"> </el-table-column>
      <el-table-column prop="stoptime" label="到期时间"> </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
        v-if="this.userType == 1 ? true : false"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="getMacAddress(scope.row.id)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card v-show="show1">
          <div id="J_chartPieBox" class="chart-box"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card v-show="show2">
          <div id="J_chartPieBox2" class="chart-box"></div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card v-show="show3">
          <div id="J_chartBarBox" class="chart-box"></div>
        </el-card>
      </el-col>
    </el-row>
    <!-- MAC地址 -->
    <el-dialog title="MAC地址" :visible.sync="dialogTableVisible">
      <el-switch
        v-model="macStatus"
        @change="onChange"
        active-color="#13ce66"
        inactive-color="#ff4949"
      >
      </el-switch>
      <el-table :data="macList" v-loading="macListLoading">
        <el-table-column
          property="macAddress"
          label="MAC地址"
          width="200"
        ></el-table-column>
        <el-table-column property="allow" label="解锁" width="200">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.allow"
              @change="onChange2($event, scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="deleteMac(scope.row.id, scope.row.macId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import echarts from "echarts";
import Vue from "vue";
export default {
  data() {
    return {
      userId: null,
      userType: null,
      show1: true,
      show2: true,
      show3: true,
      chartBar: null,
      chartPie: null,
      chartPie2: null,
      pieData: [],
      pieData2: [],
      barData: [],
      dataForm: [],
      cityList: [],
      dialogTableVisible: false,
      macStatus: null,
      macListLoading: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      qjdate: "",
    };
  },
  // mounted() {
  //   console.log("mounted")
  //   this.initBarData();
  //   this.initPieData();
  //   this.initPieData2();
  // },
  created() {
    this.userId = this.$cookie.get("userId");
    this.userType = this.$store.state.user.type;
    this.init();
  },
  methods: {
    async init() {
      await this.$http({
        url: this.$http.adornUrl(
          `/sf/city/getCityListByUserId2/${this.userId}`
        ),
        method: "get",
      }).then(({ data }) => {
        console.log(data);
        this.cityList = data.cityList;
        this.dataForm = data.cid;
        this.getHome();
      });
    },
    async getHome() {
      this.initBarData();
      this.initPieData();
      this.initPieData2();
      this.getDataList();
    },
    // 获取用户分页数据
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/sf/city/getUserListByCid"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          cid: this.dataForm[this.dataForm.length - 1],
          startdate: this.qjdate != null ? this.qjdate[0] : null,
          stopdate: this.qjdate != null ? this.qjdate[1] : null,
        }),
      }).then(({ data }) => {
        // 由于给echart添加了resize事件, 在组件激活时需要重新resize绘画一次, 否则出现空白bug
        if (this.chartBar) {
          this.chartBar.resize();
        }
        if (this.chartPie) {
          this.chartPie.resize();
        }
        if (this.chartPie2) {
          this.chartPie2.resize();
        }
        if (data && data.code === 0) {
          this.dataList = data.userPage.records;
          this.totalPage = data.userPage.total;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 初始化账号开通数量数据
    async initPieData() {
      await this.$http({
        url: this.$http.adornUrl(
          `/sf/city/getUserNum/${this.dataForm[this.dataForm.length - 1]}`
        ),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data);
          if (data.pieData == null || data.pieData.length == 0) {
            this.show1 = false;
          } else {
            this.show1 = true;
          }
          this.pieData = data.pieData;
          if (this.chartPie) {
            this.chartPie.resize();
          }
          this.initChartPie();
        }
      });
    },
    // 初始化账号登录次数数据
    async initPieData2() {
      await this.$http({
        url: this.$http.adornUrl(
          `/sf/city/getUserLoginNum/${this.dataForm[this.dataForm.length - 1]}`
        ),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data);
          if (data.pieData2 == null || data.pieData2.length == 0) {
            this.show2 = false;
          } else {
            this.show2 = true;
          }
          this.pieData2 = data.pieData2;
          if (this.chartPie2) {
            this.chartPie2.resize();
          }
          this.initChartPie2();
        }
      });
    },
    // 初始化账号登录时间
    async initBarData() {
      await this.$http({
        url: this.$http.adornUrl(
          `/sf/city/getUserLoginTime/${this.dataForm[this.dataForm.length - 1]}`
        ),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          if (data.barData == null || data.barData.length == 0) {
            this.show3 = false;
          } else {
            this.show3 = true;
          }
          this.barData = data.barData;
          if (this.chartBar) {
            this.chartBar.resize();
          }
          this.initChartBar();
        }
      });
    },
    // 柱状图
    initChartBar() {
      var x = [];
      var y = [];
      for (var i = 0; i < this.barData.length; i++) {
        x.push(this.barData[i].name);
        y.push(this.barData[i].value);
      }
      var option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          data: ["登录时间"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: x,
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
        series: [
          {
            name: "登录时间",
            type: "bar",
            data: y,
          },
        ],
      };
      this.chartBar = echarts.init(document.getElementById("J_chartBarBox"));
      this.chartBar.setOption(option);
      window.addEventListener("resize", () => {
        this.chartBar.resize();
      });
    },
    // 饼状图
    initChartPie() {
      var option = {
        backgroundColor: "#2c343c",
        title: {
          text: "账号开通数量",
          left: "center",
          top: 20,
          textStyle: {
            color: "#ccc",
          },
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        visualMap: {
          show: false,
          min: 80,
          max: 600,
          inRange: {
            colorLightness: [0, 1],
          },
        },
        series: [
          {
            name: "账号开通数量",
            type: "pie",
            radius: "55%",
            center: ["50%", "50%"],
            data: this.pieData.sort(function (a, b) {
              return a.value - b.value;
            }),
            roseType: "radius",
            label: {
              normal: {
                textStyle: {
                  color: "rgba(255, 255, 255, 0.3)",
                },
              },
            },
            labelLine: {
              normal: {
                lineStyle: {
                  color: "rgba(255, 255, 255, 0.3)",
                },
                smooth: 0.2,
                length: 10,
                length2: 20,
              },
            },
            itemStyle: {
              normal: {
                color: "#c23531",
                shadowBlur: 200,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            animationType: "scale",
            animationEasing: "elasticOut",
            animationDelay: function (idx) {
              return Math.random() * 200;
            },
          },
        ],
      };
      this.chartPie = echarts.init(document.getElementById("J_chartPieBox"));
      this.chartPie.setOption(option);
      window.addEventListener("resize", () => {
        this.chartPie.resize();
      });
    },
    // 饼状图
    initChartPie2() {
      var option = {
        backgroundColor: "#2c343c",
        title: {
          text: "账号登录次数",
          left: "center",
          top: 20,
          textStyle: {
            color: "#ccc",
          },
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        visualMap: {
          show: false,
          min: 80,
          max: 600,
          inRange: {
            colorLightness: [0, 1],
          },
        },
        series: [
          {
            name: "账号登录次数",
            type: "pie",
            radius: "55%",
            center: ["50%", "50%"],
            data: this.pieData2.sort(function (a, b) {
              return a.value - b.value;
            }),
            roseType: "radius",
            label: {
              normal: {
                textStyle: {
                  color: "rgba(255, 255, 255, 0.3)",
                },
              },
            },
            labelLine: {
              normal: {
                lineStyle: {
                  color: "rgba(255, 255, 255, 0.3)",
                },
                smooth: 0.2,
                length: 10,
                length2: 20,
              },
            },
            itemStyle: {
              normal: {
                color: "#c23531",
                shadowBlur: 200,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            animationType: "scale",
            animationEasing: "elasticOut",
            animationDelay: function (idx) {
              return Math.random() * 200;
            },
          },
        ],
      };
      this.chartPie2 = echarts.init(document.getElementById("J_chartPieBox2"));
      this.chartPie2.setOption(option);
      window.addEventListener("resize", () => {
        this.chartPie2.resize();
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 根据用户id获取MAC地址
    getMacAddress(userId) {
      this.macListLoading = true;
      this.$http({
        url: this.$http.adornUrl(`/sf/frontuser/getMacAddress/${userId}`),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data);
          this.macList = data.map[0].macId == null ? [] : data.map; // 用的左外连接
          this.macStatus = data.map[0].macStatus == 1;
          for (let i = 0; i < data.map.length; i++) {
            data.map[i].allow = data.map[i].allow == 1;
          }
          this.userId = data.map[0].id;
        } else {
          this.macList = [];
        }
        this.dialogTableVisible = true;
        this.macListLoading = false;
      });
    },
    // 开关MAC
    onChange(macStatus) {
      macStatus = macStatus ? 1 : 0;
      this.$http({
        url: this.$http.adornUrl(`/sf/frontuser/updateMacStatus`),
        method: "post",
        data: this.$http.adornData({ macStatus, id: this.userId }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
          });
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    onChange2(allow, mac) {
      allow = allow ? 1 : 0;
      let count = 0;
      for (let i = 0; i < this.macList.length; i++) {
        if (this.macList[i].allow) {
          count++;
        }
      }
      if (allow && count > 2) {
        mac.allow = false;
        this.$message.error("只允许解锁两个");
        return;
      }
      this.$http({
        url: this.$http.adornUrl(`/sf/frontuser/updateAllow`),
        method: "post",
        data: this.$http.adornData({ macId: mac.macId, allow }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
          });
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 删除MAC地址
    deleteMac(userId, macId) {
      this.$confirm(`确定对[MACid=${macId}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/macaddress/delete"),
            method: "post",
            data: this.$http.adornData([macId], false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getMacAddress(userId);
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss">
.mod-demo-echarts {
  > .el-alert {
    margin-bottom: 10px;
  }
  > .el-row {
    margin-top: -10px;
    margin-bottom: -10px;
    .el-col {
      padding-top: 10px;
      padding-bottom: 10px;
    }
  }
  .chart-box {
    min-height: 400px;
  }
}
</style>